
const ctxPath = document.getElementById("ctxPath").value;
//底部日期
document.getElementById('datetime').innerHTML = new Date().getFullYear();
let initVar = {
    "homeInfo": {
        "title": "首页",
        "href": ctxPath+"/homePage",
        "target":"_self",
    },
    "logoInfo": {
        "title": "E接口监测系统",
        "image": "img/skin/wummq27g.png",
        "href": ""
    },
    "menuInfo": [
        {
            "title": "快捷菜单",
            "icon": "iconfont icon-a-zu-1",
            "href": "",
            "target": "_self",
            "child": [
                {
                    "title": "快捷菜单",
                    "href": "",
                    "icon": "iconfont icon-a-zu-1",
                    "target": "_self",
                    "child":[
                        {
                            "title": "系统首页",
                            "icon": "",
                            "href": ctxPath+"/homePage",
                            "target": "_self"
                        }
                    ]
                }
            ]
        },
        {
            "title": "E接口监测",
            "icon": "iconfont icon-xitong",
            "href": "",
            "target": "_self",
            "child": [
                {
                    "title": "E接口信令数据查询",
                    "icon": "iconfont icon-a-zu-37\n",
                    "href": ctxPath + "/EInterface/EInterfaceMapView",
                    "target": "_self",
                    "child": []
                    // "title": "E接口信令",
                    // "icon": "iconfont icon-a-zu-37\n",
                    // "href": "",
                    // "target": "_self",
                    // "child": [
                    //     {
                    //         "title": "MAP",
                    //         "href": ctxPath + "/EInterface/EInterfaceMapView",
                    //         "icon": "",
                    //         "target": "_self",
                    //     },
                        // {
                        //     "title": "ISUP",
                        //     "href": ctxPath + "/EInterface/EInterfaceIsupView",
                        //     "icon": "",
                        //     "target": "_self",
                        // }
                    // ]
                },
                {
                    "title": "E接口切换记录查询",
                    "icon": "iconfont icon-a-zu-37\n",
                    "href": ctxPath + "/EInterface/EInterfaceHoView",
                    "target": "_self",
                    "child": []
                },
                {
                    "title": "E接口呼叫记录查询",
                    "icon": "iconfont icon-a-zu-37\n",
                    "href": ctxPath + "/EInterfaceCsd/EInterfaceCsdCallRecView",
                    "target": "_self",
                    "child": []
                },
                {
                    "title": "E接口业务数据查询",
                    "icon": "iconfont icon-a-zu-37\n",
                    "href": ctxPath + "/EInterfaceCsd/EInterfaceCsdView",
                    "target": "_self",
                    "child": []
                }
            ]
        },
        {
            "title": "系统管理",
            "icon": "iconfont icon-xitong",
            "href": "",
            "target": "_self",
            "child": [
                {
                    "title": "用户管理",
                    "icon": "iconfont icon-a-zu-37\n",
                    "href": "",
                    "target": "_self",
                    "child": [
                        {
                            "title": "账号管理",
                            "href": ctxPath + "/system/userList",
                            "icon": "",
                            "target": "_self",
                        },
                        {
                            "title": "操作日志",
                            "href": ctxPath + "/system/systemLog",
                            "icon": "",
                            "target": "_self",
                        }
                    ]
                },
            ]
        },

    ]
}
layui.use(['jquery', 'layer', 'miniAdmin', 'miniTongji','element','util','miniTab','miniMenu'], async function () {
    var element = layui.element;
    var util = layui.util;
    var miniTab = layui.miniTab;
    var miniMenu = layui.miniMenu;

    var $ = layui.jquery,
        layer = layui.layer,
        miniAdmin = layui.miniAdmin,
        miniTongji = layui.miniTongji;

    //判断菜单权限，
    let authorities =  window.sessionStorage.getItem("authorities");
    if (authorities.includes("普通用户")) {
        initVar.menuInfo.splice(2, 1);
    }

    var options = {
        iniUrl: null,    // 初始化接口
        clearUrl: "<%=basePath%>/static/layuimini/api/clear.json", // 缓存清理接口
        urlHashLocation: true,      // 是否打开hash定位
        bgColorDefault: false,      // 主题默认配置
        multiModule: true,          // 是否开启多模块
        menuChildOpen: true,       // 是否默认展开菜单
        loadingTime: 0,             // 初始化加载时间
        pageAnim: true,             // iframe窗口动画
        maxTabNum: 20,              // 最大的tab打开数量
        menuData: initVar            //初始化菜单
    };

    //初始化快捷菜单
    let quickMenuData = await getMenuInfo();
    if(quickMenuData != null){
        initVar.menuInfo[0].child[0].child = quickMenuData;
    }


    miniAdmin.render(options);

    $('.layuimini-menu-left .layui-nav').width(220);


    // 百度统计代码，只统计指定域名
    miniTongji.render({
        specific: true,
        domains: [],
    });

    $('.login-out').on("click", function () {
        layer.msg('退出登录成功', function () {
            parent.location.href = '/gydz/login';
        });
    });

    //初始化时初始化首页
    var tab = location.hash.replace(/^#\//, '')
    if(tab === '' || tab === null || tab === initVar.menuInfo[0].child[0].child[0].href){
        miniTab.listenSwitchMultiModule(initVar.menuInfo[0].child[0].child[0].href);
        miniTab.openNewTabByIframe(initVar.menuInfo[0].child[0].child[0])
        miniTab.rollPosition();
    }

    var selectedValues = []; // 存储选中复选框的值

    bindQuickMenuEvents();

    function bindQuickMenuEvents(){
        $('.icon-button-quick').on("click", function () {
            layer.open({
                type: 1,
                area: ['720px','600px'],
                resize: false,
                shadeClose: true,
                closeBtn: 1,
                title: '快捷菜单设置',
                content: `
          <div style="">
            <div class="table-container">
                <div class="table-header">已选菜单<span class="table-header-span">按住菜单标签可以对菜单进行排序，最多可以设置15个快捷菜单</span></div>
                <div class="selected-tags" style="max-height: 80px;overflow-y: auto;margin-bottom: 13px"></div>
                    <div class="clearfix">
                        <div class="checkbox-column">
                            <h3>E接口监测</h3>
                            <label class="checkbox-label"><input type="checkbox" data-value="/EInterface/EInterfaceMapView"> E接口信令数据查询</label>
                            <label class="checkbox-label"><input type="checkbox" data-value="/EInterface/EInterfaceHoView"> E接口切换记录查询</label>
                            <label class="checkbox-label"><input type="checkbox" data-value="/EInterfaceCsd/EInterfaceCsdCallRecView"> E接口呼叫记录查询</label>
                            <label class="checkbox-label"><input type="checkbox" data-value="/EInterfaceCsd/EInterfaceCsdView"> E接口业务数据查询</label>
                        </div>
                        
                        <div class="checkbox-column">
                            <h3>系统管理</h3>
                            <label class="checkbox-label"><input type="checkbox" data-value="/system/userList"> 账号管理</label>
                            <label class="checkbox-label"><input type="checkbox" data-value="/system/systemLog"> 操作日志</label>
                        </div>
                        
                    </div>
            </div>
          </div>
        `,
                success: async function(layero, index){

                    const jsonObject = await getMenuInfo();
                    // 初始化选中的复选框
                    if(jsonObject == null){
                        initSelectedValues(); //初始化菜单数组
                    }else {
                        //遍历jsonObject的每个元素,置checkbox复选框
                        for (const key in jsonObject) {
                            if (jsonObject.hasOwnProperty(key)) {
                                const value = jsonObject[key];
                                const startIndex = value.href.indexOf(ctxPath) + ctxPath.length;
                                const result = value.href.substring(startIndex);
                                // 找到对应的复选框并设置选中状态
                                $(layero).find(`input[data-value="${result}"]`).prop('checked', true);
                            }
                        }
                        selectedValues = jsonObject;
                    }
                    updateSelectedTags(layero);

                    // 绑定复选框的变化事件
                    $(layero).find('input[type="checkbox"]').on('change', async function() {
                        if ($(this).prop('checked') && selectedValues.length >= 16) {
                            // 如果复选框被选中且已经达到上限
                            $(this).prop('checked', false); // 取消当前复选框的选中状态
                            layer.msg('菜单已到达限定数量，请先取消勾选其他菜单');
                            return;
                        }

                        var value = $(this).data('value'); // 获取当前复选框的数据值
                        var text = $(this).closest('label').text().trim(); // 获取当前复选框的文本
                        let obj = {
                            title: text,
                            icon:"",
                            href: ctxPath +value,
                            target: '_self',
                        }
                        if ($(this).prop('checked')) {
                            // 如果复选框被选中，添加到已选中数组中
                            if (!selectedValues.includes(obj)) {
                                selectedValues.push(obj);
                            }
                        } else {
                            // 如果取消选中，从数组中移除
                            selectedValues = selectedValues.filter(function(item) {
                                return item.title !== text;
                            });
                        }
                        updateSelectedTags(layero);
                        await setMenuInfo(selectedValues);
                    });

                    // 绑定按钮点击事件
                    $(layero).find('.confirm-button').on('click', function() {
                        // 关闭弹窗
                        layer.close(index);
                    });

                    $(layero).find('.cancel-button').on('click', function() {
                        // 关闭弹窗
                        layer.close(index);
                    });

                    var $jq = jQuery.noConflict();
                    $jq(document).ready(function() {
                        $jq('.selected-tags').sortable(
                            {
                                items: ':not(.fixed-tag)',
                                update: async function(event, ui) {
                                    initSelectedValues()
                                    $jq('.selected-tags').children('.tag').each(function() {
                                        var spanValue = $(this).text().trim();
                                        var value = $(this).attr('value'); // 获取当前复选框的数据值
                                        // 去掉删除图标的文本
                                        var labelValue = spanValue.replace(/×$/, '').trim();
                                        let obj = {
                                            title: labelValue,
                                            icon:"",
                                            href: ctxPath +value,
                                            target: '_self',
                                        }
                                        if(labelValue !== "系统首页"){
                                            selectedValues.push(obj);
                                        }
                                    });
                                    await setMenuInfo(selectedValues);
                                }
                            }
                        );
                    });
                },
                cancel: function(){ //取消 后回调方法
                    initVar.menuInfo[0].child[0].child = selectedValues;
                    refreshMenu();
                },
            });
        });
    }

    function initSelectedValues(){
        selectedValues = [];
        let obj = {
            title: "系统首页",
            icon:"",
            href: ctxPath+"/homePage",
            target: '_self',
        }
        selectedValues.push(obj)
    }

    function updateSelectedTags(layero) {
        var tagsContainer = $(layero).find('.selected-tags');
        tagsContainer.empty(); // 清空当前显示的标签

        var tagInit = $('<span class="tag fixed-tag"></span>').css({
            display: 'inline-flex', // 使用 inline-flex 以便内容自适应宽度
            alignItems: 'center',   // 垂直居中对齐
            margin: '0px 8px 8px 0px',
            padding: '8px 10px',
            backgroundColor: '#F8F8F8',
            color: '#707070',
            borderRadius: '3px',
            border: '1px solid #DDDDDD',
            whiteSpace: 'nowrap'    // 防止内容换行
        }).text('系统首页').attr('value', '/homePage');
        var removeIconInit = $('<span class="remove-icon">&times;</span>').css({
            marginLeft: '10px',
            color: '#707070',
            cursor: 'pointer',
            fontWeight: 'bold'
        });
        tagInit.append(removeIconInit);
        tagsContainer.append(tagInit);

        // 添加其他选中的标签
        selectedValues.forEach(function(item, index) {
            let value = item.href.replace(ctxPath, '');
            if (index > 0) { // 跳过系统首页
                var tag = $('<span class="tag"></span>').css({
                    display: 'inline-flex', // 使用 inline-flex 以便内容自适应宽度
                    alignItems: 'center',   // 垂直居中对齐
                    margin: '0px 8px 8px 0px',
                    padding: '8px 10px',
                    backgroundColor: '#007bff',
                    color: 'white',
                    borderRadius: '3px',
                    whiteSpace: 'nowrap'    // 防止内容换行
                }).text(item.title).attr('value', value);

                var removeIcon = $('<span class="remove-icon">&times;</span>').css({
                    marginLeft: '10px',
                    color: 'white',
                    cursor: 'pointer',
                    fontWeight: 'bold'
                });

                // 绑定点击事件到删除图标
                removeIcon.on('click', async function() {
                    $(this).parent().remove();
                    // 同步取消复选框的选中状态
                    $(layero).find('input[type="checkbox"][data-value="' + value + '"]').prop('checked', false);
                    selectedValues = selectedValues.filter(function(obj) {
                        return obj.title !== item.title;
                    });
                    await setMenuInfo(selectedValues);
                });

                tag.append(removeIcon);
                tagsContainer.append(tag);
            }
        });
    }

    function refreshMenu(){
        miniMenu.render({
            menuList: options.menuData.menuInfo,
            multiModule: options.multiModule,
            menuChildOpen: options.menuChildOpen
        })
        // miniAdmin.render(options);
        $('.layuimini-menu-left .layui-nav').width(220);

        bindQuickMenuEvents();
    }

    function getMenuInfo() {
        return new Promise((resolve, reject) => {
            try {
                $.ajax({
                    url: ctxPath + '/shortcutMenu/getMenuInfo',
                    type: 'get',
                    dataType: 'json',
                    success: function (data) {
                        let menuInfo = data.menuInfo ? JSON.parse(data.menuInfo) : initMenuInfo();
                        resolve(menuInfo);
                    },
                    error: function (error) {
                        resolve(initMenuInfo());
                    }
                })
            } catch (error) {
                reject(error);
            }
        });
    }

    function setMenuInfo(menuInfo) {
        return new Promise((resolve, reject) => {
            try {
                let formData = {
                    menuInfo: JSON.stringify(menuInfo)
                }
                $.ajax({
                    url: ctxPath + '/shortcutMenu/save',
                    type: 'post',
                    dataType: 'json',
                    data: formData,
                    success: function (data) {
                        window.sessionStorage.setItem("shortcut_menu", JSON.stringify(menuInfo));
                        resolve();
                    }
                })
            } catch (error) {
                reject(error);
            }
        });
    }

    function initMenuInfo(){
        return [
            {
                title: "系统首页",
                icon: "",
                href: ctxPath + "/homePage",
                target: '_self',
            }
        ];
    }





});

Vue.config.productionTip = false
new Vue({
    el: '#app',
    data(){
        return {
            account: null,
            updateUserShow:{
                sectionName: true,
                workshop: true,
                workArea: true,
                updateSectionNameShow: true,
                updateworkshopShow: true,
                updateworkAreaShow: true,
            },
            sectionNameOption:[],
            workshopOption:[],
            workAreaOption:[],
            updateUserDialog: false,
            updateUserForm: {
                id: '',
                userName: '',
                password: '',
                rid: '',
                deptName: '电务部',
                sectionName: '',
                workshop: '',
                workArea: '',
                accountAttributes: ''
            },
            updatePwdDialog: false,
            updatePwdForm: {
                updateId: '',
                updateAccount: '',
                updatePwd: '',
                checkPass: '',
            },
            updatePwdRules: {
                updatePwd: {required: true, message: '请输入新密码', trigger: 'blur'},
                checkPass: {required: true, message: '请输入确认密码', trigger: 'blur'},
            },
            name: '',
        }
    },
    created(){

    },

    mounted() {
        this.account = $("#userName").text();
    },

    methods: {

        updateUserOpen(){
            let me = this;
            $.ajax({
                type: "post",
                url: ctxPath + "/system/userInfoByName",
                data: "account=" + this.account,
                dataType: "json",
                success: function (data1) {
                    data1 = data1.data;
                    me.updateUserForm.account = data1.account;
                    me.updateUserForm.id = data1.id;
                    me.updateUserForm.userName = data1.userName;
                    me.updateUserForm.password = data1.password;
                    me.updateUserPwd = data1.password;
                    me.updateUserForm.sectionName = data1.sectionName;
                    me.updateUserForm.workshop = data1.workshop;
                    me.updateUserForm.workArea = data1.workArea;
                    me.updateUserForm.accountAttributes = data1.accountAttributes;
                    me.updateUserShow.updateSectionNameShow = true;
                    me.updateUserShow.updateworkshopShow = true;
                    me.updateUserShow.updateworkAreaShow = true;
                    $.ajax({
                        type: "post",
                        url: ctxPath + "/system/user/getItems",
                        data: "colName=cname",
                        dataType: "json",
                        complete: function (data) {
                            data = data.responseJSON;
                            me.sectionNameOption = data.data;
                            me.sectionNameOption.push({ value: '其他', label: '其他' });
                            me.updateUserForm.sectionName = me.updateUserForm.sectionName == undefined ? '' : me.updateUserForm.sectionName;
                        }
                    });
                    if(me.updateUserForm.sectionName != undefined){
                        $.ajax({
                            type: "post",
                            url: ctxPath + "/system/user/getItems",
                            data: "colName=tname&cname=" + me.updateUserForm.sectionName,
                            dataType: "json",
                            complete: function (data) {
                                me.workshopOption = data.responseJSON.data;
                                me.workshopOption.push({ value: '其他', label: '其他' });
                            }
                        });
                    }
                    if(me.updateUserForm.workshop != undefined){
                        $.ajax({
                            type: "post",
                            url: ctxPath + "/system/user/getItems",
                            data: "colName=wname&cname=" + me.updateUserForm.sectionName + "&tname=" + me.updateUserForm.workshop,
                            dataType: "json",
                            complete: function (data) {
                                me.workAreaOption = data.responseJSON.data;
                                me.workAreaOption.push({ value: '其他', label: '其他' });
                            }
                        });
                    }

                    me.updateUserDialog = true;
                }
            });
        },

        //站段下拉框点击事件
        sectionNameSelectChange(val){
            if(val == '其他'){
                this.updateUserForm.sectionName = '';
                this.updateUserShow.updateSectionNameShow = false;
            }
            let me = this;
            $.ajax({
                type: "post",
                url: ctxPath + "/system/user/getItems",
                data: "colName=tname&cname=" + val,
                dataType: "json",
                complete: function (data) {
                    me.workshopOption = data.responseJSON.data;
                    me.workshopOption.push({ value: '其他', label: '其他' });
                    me.updateUserShow.updateworkshopShow = true;
                    me.updateUserForm.workshop = '';
                    me.updateUserForm.workArea = '';
                }
            });
        },
        //车间下拉框点击事件
        workshopSelectChange(val){
            if(val == '其他'){
                this.updateUserForm.workshop = '';
                this.updateUserShow.updateworkshopShow = false;
            }
            let me = this;
            $.ajax({
                type: "post",
                url: ctxPath + "/system/user/getItems",
                data: "colName=wname&cname=" + me.updateUserForm.sectionName + "&tname=" + val,
                dataType: "json",
                complete: function (data) {
                    me.workAreaOption = data.responseJSON.data;
                    me.workAreaOption.push({ value: '其他', label: '其他' });
                    me.updateUserShow.updateworkAreaShow = true;
                    me.updateUserForm.workArea = '';
                }
            });
        },
        //工区下拉框点击事件
        workAreaSelectChange(val) {
            if (val == '其他') {
                this.updateUserForm.workArea = '';
                this.updateUserShow.updateworkAreaShow = false;
            }
        },
        //修改用户信息
        updateUser(formName){
            let me = this;
            var workshop = me.updateUserForm.workshop != undefined ? me.updateUserForm.workshop : '';
            switch (me.updateUserForm.accountAttributes) {
                case "电务部":
                    this.updateUserForm.sectionName = '';
                    this.updateUserForm.workshop = '';
                    this.updateUserForm.workArea = '';
                    break;
                case "站段":
                    this.updateUserForm.workArea = '';
                    break;
                case "车间":
                    this.updateUserForm.workArea = '';
                    break;
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.updateUserForm.password == this.updateUserPwd){
                        this.updateUserForm.password = null;
                    }
                    $.ajax({
                        type: "post",
                        url: ctxPath + "/system/user/updateUser",
                        data: this.updateUserForm,
                        dataType: "json",
                        complete: function (data) {
                            data = data.responseJSON;
                            console.log(data);
                            if (data.code === 200 && data.data > 0) {
                                me.$message({
                                    message: '修改成功！',
                                    type: 'success',
                                    duration: 1000,
                                    showClose: true
                                });
                                me.updateUserDialog = false;
                                location.reload();
                            } else {
                                me.$message.error('修改失败，请联系系统管理员');
                                me.updateUserDialog = false;
                                me.queryData();
                            }
                        },
                        error: function (XmlHttpRequest, textStatus, errorThrown) {
                            console.log("error");
                        },
                    });
                } else {
                    return false;
                }
            });
            me.updateUserForm.workshop = workshop;
        },

        //关闭修改密码窗口
        updateUserClose(formName){
            this.updateUserDialog = false;
            this.$refs[formName].resetFields();
        },

        //打开修改用户密码窗口
        updatePwdOpen(id,account){
            let me = this;
            $.ajax({
                type: "post",
                url: ctxPath + "/system/userInfoByName",
                data: "account=" + this.account,
                dataType: "json",
                success: function (data) {
                    data = data.data;
                    me.updatePwdForm.updateId = data.id
                    me.updatePwdDialog = true;
                }
            })
        },
        //关闭修改密码窗口
        updatePwdClose(formName){
            this.updatePwdDialog = false;
            this.$refs[formName].resetFields();
        },
        //修改密码
        updatePwd(formName) {
            let me = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.updatePwdForm.updatePwd != this.updatePwdForm.checkPass){
                        this.$message.error('两次输入密码不一致，请重新输入');
                        return;
                    }
                    $.ajax({
                        type: "POST",
                        url: ctxPath + "/system/user/updateUserPwd",
                        data: "id=" + this.updatePwdForm.updateId + '&password=' + this.updatePwdForm.updatePwd,
                        dataType: "json",
                        complete: function (data) {
                            data = data.responseJSON;
                            if (data.code === 200 && data.data === true) {
                                me.$message({
                                    message: '修改成功！',
                                    type: 'success',
                                    duration: 1000,
                                    showClose: true
                                });
                                me.updatePwdForm.updateAccount = '';
                                me.updatePwdForm.updateId = '';
                                me.updatePwdForm.updatePwd = '';
                                me.updatePwdForm.checkPass = '';
                                me.updatePwdDialog = false;
                                me.queryData();
                            } else {
                                me.$message.error('修改密码失败，请联系系统管理员');
                                me.queryData();
                            }
                        },
                        error: function (XmlHttpRequest, textStatus, errorThrown) {
                            console.log("error");
                        },
                    });
                } else {
                    return false;
                }
            });
        },


    }

})